#!/bin/bash

source ../scripts/common.sh

PHP_SWOOLE_VER=5.0.0
PHP_SWOOLE_MD5SUM=38ae7320042452b8362d01c704c40e88

PHP8_BASE_PATH=/usr/local/php
read -p "请输入PHP8的安装路径($PHP8_BASE_PATH):"  PHP8_BASE_PATH

# 确定PHP8 安装路径
if [ -n $PHP8_BASE_PATH ]; then
PHP8_BASE_PATH=/usr/local/php
fi

if [ ! -f "${PHP8_BASE_PATH}/bin/php" ]; then
    echo -e "\033[31m[ERROR]\033[0m 请先安装PHP"
    exit 0;
fi

echo "\033[32m [SUCCESS]\033[0m Swoole 将被安装到: $PHP8_BASE_PATH 所在目录.\033[0m";

download https://github.com/swoole/swoole-src/archive/v$PHP_SWOOLE_VER.tar.gz swoole-src-$PHP_SWOOLE_VER.tar.gz $PHP_SWOOLE_MD5SUM

if [ ! -d "swoole-src-$PHP_SWOOLE_VER" ]; then  tar -xvf swoole-src-$PHP_SWOOLE_VER.tar.gz; fi

if [ -n $PHP8_BASE_PATH ] && [ -f "${PHP8_BASE_PATH}/bin/php" ]; then
    pushd  swoole-src-$PHP_SWOOLE_VER
    ${PHP8_BASE_PATH}/bin/phpize && \
    ./configure --enable-openssl --enable-swoole-json --enable-sockets --enable-http2 --enable-swoole-curl --with-php-config=${PHP8_BASE_PATH}/bin/php-config && \
    make clean && make -j${THREAD_NUM} && make install
    popd

    PHP_VERSION=`${PHP8_BASE_PATH}/bin/php -v | grep "^PHP [0-9]" | cut -c 5-7`

    cp ${PHP8_BASE_PATH}/etc/php.ini ${PHP8_BASE_PATH}/etc/swoole.ini
    sed -i '/;extension=soap/i\extension=swoole.so' ${PHP8_BASE_PATH}/etc/swoole.ini

    case ${PHP_VERSION} in
        "7.0"|"7.1"|"7.2"|"7.3"|"7.4")
            echo -e "\033[32m [SUCCESS]\033[0m 当前PHP版本是 PHP-${PHP_VERSION}. 将开启Opcache"
            # 开启opcache加速
            sed -i 's#opcache.enable=1#;opcache.enable=1#' ${PHP8_BASE_PATH}/etc/swoole.ini
            sed -i 's#opcache.enable_cli=1#;opcache.enable_cli=1#' ${PHP8_BASE_PATH}/etc/swoole.ini

            # 关闭文件检测
            sed -i 's#;opcache.validate_timestamps=1#;opcache.validate_timestamps=0#' ${PHP8_BASE_PATH}/etc/swoole.ini
            # 设置文件检测间隔300秒
            sed -i 's#;opcache.revalidate_freq=0#;opcache.revalidate_freq=300#' ${PHP8_BASE_PATH}/etc/swoole.ini
            ;;
        "8.0"|"8.1"|"8.2")
            echo -e "\033[32m [SUCCESS]\033[0m 当前PHP版本是 PHP-${PHP_VERSION}. 将开启Opcache+JIT"
            ;;
        *)
            echo -e "\033[31m[ERROR]\033[0m 未知的PHP版本"
    esac
fi
